import React from 'react'
import { useSelector } from 'react-redux'
import { Result, Button } from 'antd'
import { useRouter } from 'next/router'

const PermissionGuard = ({ 
  children, 
  requiredPermissions = [], 
  requiredRole = null,
  fallback = null 
}) => {
  const { user, isAuthenticated } = useSelector(state => state.auth)
  const router = useRouter()

  // 检查是否已登录
  if (!isAuthenticated) {
    return (
      <Result
        status="403"
        title="未授权访问"
        subTitle="请先登录系统"
        extra={
          <Button type="primary" onClick={() => router.push('/login')}>
            去登录
          </Button>
        }
      />
    )
  }

  // 检查角色权限
  if (requiredRole && user?.role !== requiredRole) {
    return fallback || (
      <Result
        status="403"
        title="权限不足"
        subTitle="您没有访问此页面的权限"
        extra={
          <Button type="primary" onClick={() => router.back()}>
            返回
          </Button>
        }
      />
    )
  }

  // 检查具体权限
  if (requiredPermissions.length > 0) {
    const userPermissions = user?.permissions || []
    const hasPermission = requiredPermissions.every(permission =>
      userPermissions.includes(permission)
    )

    if (!hasPermission) {
      return fallback || (
        <Result
          status="403"
          title="权限不足"
          subTitle="您没有执行此操作的权限"
          extra={
            <Button type="primary" onClick={() => router.back()}>
              返回
            </Button>
          }
        />
      )
    }
  }

  return children
}

export default PermissionGuard

// 权限检查 Hook
export const usePermission = () => {
  const { user } = useSelector(state => state.auth)

  const hasPermission = (permission) => {
    return user?.permissions?.includes(permission) || false
  }

  const hasRole = (role) => {
    return user?.role === role
  }

  const hasAnyPermission = (permissions) => {
    return permissions.some(permission => hasPermission(permission))
  }

  const hasAllPermissions = (permissions) => {
    return permissions.every(permission => hasPermission(permission))
  }

  return {
    hasPermission,
    hasRole,
    hasAnyPermission,
    hasAllPermissions,
    userPermissions: user?.permissions || [],
    userRole: user?.role,
  }
}